package com.ddstation.crm.organization_structure.service;

import com.ddstation.crm.institution.entity.DtHealthManageInstitutionDoctorEntity;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionDoctorMapper;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.crm.organization_structure.entity.DtInvsOrganizationStructureEntity;
import com.ddstation.crm.organization_structure.mapper.DtInvsOrganizationStructureMapper;
import com.ddstation.crm.organization_structure.mapper.DtInvsOrganizationStructureStaffMapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service @Lazy
public class OrgServiceImpl implements OrgService {

	@Override
	@Transactional(rollbackFor=Exception.class)
	public DtInvsOrganizationStructureEntity get(String institutionId,Integer doctorId) {
		// TODO Auto-generated method stub
		// 组织结构数据
		List<DtInvsOrganizationStructureEntity> plainOrgStructs = dtInvsOrganizationStructureMapper.select(institutionId,null);
		//获取当前用户所在组织id
		int orgId = dtInvsOrganizationStructureStaffMapper.selectOrgIdByDoctorId(doctorId);
		if (plainOrgStructs == null || plainOrgStructs.isEmpty()) { // 第1次使用
			DtHealthManageInstitutionEntity institution = dtHealthManageInstitutionMapper.select(institutionId);
			if (institution == null) {
				throw new IllegalStateException("机构数据不存在");
			}
			
			// 组织架构
			DtInvsOrganizationStructureEntity _root = new DtInvsOrganizationStructureEntity();
			_root.setName(institution.getName());
			_root.setInstitutionId(institution.getId());
			dtInvsOrganizationStructureMapper.insert(_root);
			
			// 组织内部医生
			DtHealthManageInstitutionDoctorEntity condition = new DtHealthManageInstitutionDoctorEntity();
			condition.setInstitution(institution);
			List<DtHealthManageInstitutionDoctorEntity> doctors = dtHealthManageInstitutionDoctorMapper.select(condition);
			if (doctors == null || doctors.isEmpty()) {
				throw new IllegalStateException("机构的医生数据不存在");
			}
			for (DtHealthManageInstitutionDoctorEntity doctor : doctors) {
//				DtInvsOrganizationStructureStaffEntity staff = new DtInvsOrganizationStructureStaffEntity();
//				DtInvsOrganizationStructureEntity org = new DtInvsOrganizationStructureEntity();
//				org.setId(_root.getId());
//				DdDoctorEntity d = new DdDoctorEntity();
//				d.setId(doctor.getId());
//				staff.setOrg(org);
//				staff.setDoctor(d);
				dtInvsOrganizationStructureStaffMapper.insert(_root.getId(), doctor.getId(), 0);
			}
			
			return _root;
		} else { // 数据库中已有数据
			DtInvsOrganizationStructureEntity root = null; // 组织架构的root
			Iterator<DtInvsOrganizationStructureEntity> iteL0 = plainOrgStructs.iterator(); // root
			while (iteL0.hasNext()) {
				DtInvsOrganizationStructureEntity o = iteL0.next();
				// 取一级分类  if (o.getParent() == null)
				// 取当前用户所在分类 if (o.getId() == orgId)
				if (o.getId() == orgId) {
					if (root != null) {
						throw new IllegalStateException("同一机构中有多个跟组织");
					} else {
						root = o;
						iteL0.remove();
					}
				}
			}
			
			// 转换成组织架构格式
			mateOrgStruct(root, plainOrgStructs);
			
			return root;
		}
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public int add(DtInvsOrganizationStructureEntity orgStruct) {
		// TODO Auto-generated method stub
		if (accessable(orgStruct.getInstitutionId(), orgStruct.getParent().getId())) {
			return dtInvsOrganizationStructureMapper.insert(orgStruct);
		} else {
			throw new IllegalStateException("非法访问");
		}
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public int replace(DtInvsOrganizationStructureEntity orgStruct) {
		// TODO Auto-generated method stub
		if (accessable(orgStruct.getInstitutionId(), orgStruct.getId())) {
			return dtInvsOrganizationStructureMapper.update(orgStruct);
		} else {
			throw new IllegalStateException("非法访问");
		}
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public int remove(DtInvsOrganizationStructureEntity orgStruct) {
		// TODO Auto-generated method stub
		if (accessable(orgStruct.getInstitutionId(), orgStruct.getId())) {
			int removeCnt = 0;
			List<Integer> coverDept = this.getCoverDept(orgStruct.getId());
			for (Integer dept : coverDept) {
				DtInvsOrganizationStructureEntity _d = new DtInvsOrganizationStructureEntity();
				_d.setId(dept);
				_d.setInstitutionId(orgStruct.getInstitutionId());
				removeCnt += dtInvsOrganizationStructureMapper.delete(_d);
			}
			return removeCnt;
		} else {
			throw new IllegalStateException("非法访问");
		}
	}
	
	/**
	 * 全部涵盖的部门部门id（包括自己）
	 * @param orgId
	 * @return
	 */
	@Override
	@Transactional(readOnly=true)
	public List<Integer> getCoverDept(int orgId) {
		// TODO Auto-generated method stub
		List<Integer> depts = new ArrayList<Integer>();
		depts.add(orgId);
		
		List<DtInvsOrganizationStructureEntity> childrens = dtInvsOrganizationStructureMapper.selectSubDept(orgId);
		if (childrens != null) {
			for (DtInvsOrganizationStructureEntity children : childrens) {
				depts.addAll(this.getCoverDept(children.getId()));
			}
		}
		return depts;
	}
	
	/**
	 * 扁平的组织架构数据转换成树状的组织架构
	 * @param node
	 * @param leafs
	 */
	private void mateOrgStruct(DtInvsOrganizationStructureEntity node, List<DtInvsOrganizationStructureEntity> leafs) {
		if (node == null || leafs == null) return;
		
		Iterator<DtInvsOrganizationStructureEntity> ite = leafs.iterator(); // root
		while (ite.hasNext()) {
			DtInvsOrganizationStructureEntity leaf = ite.next();
			if (leaf.getParent() != null) {
				if (leaf.getParent().getId().intValue() == node.getId().intValue()) {
					if (node.getChildrens() == null) node.setChildrens(new ArrayList<DtInvsOrganizationStructureEntity>());
					node.getChildrens().add(leaf);
					ite.remove();
				}
			} else {
				ite.remove();
			}
		}
		
		if (node.getChildrens() != null) {
			for (DtInvsOrganizationStructureEntity nextNode : node.getChildrens()) {
				mateOrgStruct(nextNode, leafs);
			}
		}
	}
	
	/**
	 * 验证访问合法性
	 * @param institutionId
	 * @param orgId
	 */
	private boolean accessable(String institutionId, int orgId) {
		DtInvsOrganizationStructureEntity dept = dtInvsOrganizationStructureMapper.selectByPK(orgId);
		if (dept == null) throw new IllegalStateException("组织架构不存在 orgId=" + orgId);
		
		if (!institutionId.equals(dept.getInstitutionId())) throw new IllegalStateException("组织架构不存在 orgId=" + orgId);
		
		return true;
	}
	
	@Inject private DtInvsOrganizationStructureMapper dtInvsOrganizationStructureMapper = null;
	@Inject private DtInvsOrganizationStructureStaffMapper dtInvsOrganizationStructureStaffMapper = null;
	@Inject private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper = null;
	@Inject private DtHealthManageInstitutionDoctorMapper dtHealthManageInstitutionDoctorMapper = null;
}
